/*****目标团队--目标 --攻防赛*****/
<template
  ><!---->
  <search-table
	    ref="searchTable"
		  :columns="targetTeamCol" 
      :data="targetAllotList"
      :total="targetAllotTotal"
      :page.sync="queryTargetAllotInfo.pageIndex"
      :size.sync="queryTargetAllotInfo.pageSize"
      :disabled = "(data) => {
        return this.disabledAllBtn
      }"
      showSelectTag
      :selection.sync="selectTargetTeams"
      @change-size="getTargetSize"
      @change-page="getTargetPage"
	>
  <template slot="search">
      <!-- <Checkbox
        v-model="selectAll"
        :disabled="targetAllotList.length === 0 || disabledAllBtn"
        @on-change="selectAllChange"
        style="margin-bottom:8px"
        >全选</Checkbox
      > -->
      <Poptip
        confirm
        title="你确定要删除选中的数据吗？"
        transfer
        @on-ok="batchDeleteTopoAllotTarget"
        style="margin-right:15px;"
      >
        <Button
          type="error"
          ghost
          :disabled="checkTargetIds.length === 0 || disabledAllBtn"
          icon="ios-trash-outline"
          >批量删除</Button
        >
      </Poptip>
      <Button
        type="primary"
        ghost
        @click="batchAllotTopoTarget"
        :disabled="accessGroupList.length == 0 || disabledAllBtn"
        :loading="assignLoading"
        style="margin-right:15px;"
        ><img
          src="../../../../assets/scene/target-allot-purple.png"
          alt=""
        />一键分配公共目标</Button
      >
      <Button
        type="primary"
        ghost
        @click="showAddAndUpdate('')"
        :disabled="accessGroupList.length == 0 || disabledAllBtn"
        style="margin-right:15px;"
        ><img src="../../../../assets/scene/target-allot-purple.png" alt="" />目标分配</Button
      >
      <Select filterable
        v-model="queryTargetAllotInfo.teamName"
        style="width:150px;margin-right:15px;"
        @on-change="getTargetPage(1)"
        transfer
        clearable
        filterable
        placeholder="请选择团队"
      >
        <Option
          v-for="item in accessGroupList"
          :value="item.name"
          :key="item.id"
          :title="item.name"
          >{{ item.name }}</Option
        >
      </Select>
      <Select filterable
        v-model="queryTargetAllotInfo.industry"
        placeholder="请选择行业"
        transfer
        clearable
        filterable
        style="width:150px;margin-right:15px;"
        @on-change="getTargetPage(1)"
      >
        <Option
          :value="item.dictid"
          v-for="item in industryList"
          :key="item.dictid"
          :title="item.dictname"
          >{{ item.dictname }}</Option
        >
      </Select>
      <Select filterable
        v-model="queryTargetAllotInfo.company"
        placeholder="请选择单位"
        transfer
        filterable
        clearable
        style="width:150px;margin-right:15px;"
        @on-change="getTargetPage(1)"
      >
        <Option :value="company" v-for="company in companyList" :key="company" :title="company">{{
          company
        }}</Option>
      </Select>
      <!-- <Input
        v-model.trim="queryTargetAllotInfo.company"
        placeholder="单位"
        clearable
        style="width:180px;margin-right:15px;"
        @on-change="getTargetPage(1)"
      ></Input> -->
      <Input
        v-model.trim="queryTargetAllotInfo.url"
        placeholder="Url"
        clearable
        style="width:180px;margin-right:15px;"
        @on-change="getTargetPage(1)"
      ></Input>
      <Input
        v-model.trim="queryTargetAllotInfo.name"
        placeholder="名称"
        clearable
        style="width:180px;margin-right:15px;"
        @on-change="getTargetPage(1)"
      ></Input>
      <!-- <Input
        v-model.trim="queryTargetAllotInfo.edition"
        placeholder="版本信息"
        clearable
        style="width:180px;margin-right:15px;"
        @on-change="getTargetPage(1)"
      ></Input> -->
      <!-- <Select filterable
        v-model="queryTargetTeamInfo.category"
        placeholder="请选择类别"
        filterable
        clearable
        style="width:150px"
        @on-change="getTargetPage(1)"
      >
        <Option
          :value="item.value"
          v-for="item in categoryArr"
          :key="item.value"
          :title="item.label"
          >{{ item.label }}</Option
        >
      </Select> -->
      <!--<DatePicker format="yyyy-MM-dd HH:mm:ss" type="daterange"  placeholder="选择日期" style="width: 200px"
                  @on-change="searchTargetPrjD"></DatePicker>-->
      <!--<Input v-model.trim="searchPrjString" search placeholder="目标名称" style="width: 200px" @on-search="searchTargetPrj"  />-->
  </template>
  <Modal
        v-model="targetModal.show"
        :title="targetModal.title"
        :loading="targetModal.loading"
        width="1050px"
        class="account-target-modal"
        :mask-closable="false"
        @on-visible-change="targetModalVisibleChange"
        @on-cancel="closeTargetModal"
        @on-ok="targetAllot"
      >
        <div class="search-group">
          <!-- <Input
            v-model.trim="teamName"
            placeholder="团队名称"
            style="width:150px;margin-left:16px;"
            @on-change="getDataBounce"
          ></Input> -->
          <Select filterable
            v-model="teamName"
            placeholder="请选择团队"
            @on-change="getDataBounce"
            filterable
            style="width:150px;margin-left:16px;"
          >
            <Option v-for="item in accessGroupList" :value="item.name" :key="item.id">{{
              item.name
            }}</Option>
          </Select>
          <Select filterable
            v-model="queryTargetTeamInfo.company"
            placeholder="请选择单位"
            transfer
            filterable
            clearable
            style="width:150px;margin-left:16px;"
            @on-change="
              queryTargetTeamInfo.pageIndex = 1;
              getTargetTeamList();
            "
          >
            <Option
              :value="company"
              v-for="company in companyList"
              :key="company"
              :title="company"
              >{{ company }}</Option
            >
          </Select>
          <Select filterable
            v-model="queryTargetTeamInfo.category"
            placeholder="请选择类别"
            filterable
            clearable
            style="width:150px"
            @on-change="
              queryTargetTeamInfo.pageIndex = 1;
              getTargetTeamList();
            "
          >
            <Option
              :value="item.value"
              v-for="item in categoryArr"
              :key="item.value"
              :title="item.label"
              >{{ item.label }}</Option
            >
          </Select>
          <!-- <Select filterable
            v-model="queryTargetTeamInfo.industry"
            placeholder="请选择行业"
            transfer
            filterable
            clearable
            style="width:150px;margin-left:16px;"
            @on-change="getTargetTeamList()"
          >
            <Option
              :value="item.dictid"
              v-for="item in industryList"
              :key="item.dictid"
              :title="item.dictname"
              >{{ item.dictname }}</Option
            >
          </Select> -->
        </div>
        <Form ref="formValidate" :model="formValidate" :label-width="100">
          <!--{{formValidate.accessGroupList}}-->
          <div v-for="(group, index) in formValidate.accessGroupList" :key="index">
            <FormItem label="团队">
              {{ group.name }}
              <!--<Select filterable  v-model="formValidate[$index].teamId" placeholder="请选择团队">
                  <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
                </Select>-->
            </FormItem>
            <FormItem label="已选择目标">
              <Row
                ><Tag color="blue" v-for="targetId in group.targetIds" :key="targetId"
                  >{{ idwithName[targetId] && idwithName[targetId].name }}（{{
                    (idwithName[targetId] && idwithName[targetId].groupName) || '无'
                  }}）（{{
                    idwithName[targetId] && idwithName[targetId].category
                      ? filterCategory(idwithName[targetId].category)
                      : '无'
                  }}）</Tag
                ></Row
              >
            </FormItem>
            <FormItem label="所有目标" :prop="'accessGroupList.' + index + '.targetIds'">
              <!--<Select filterable v-model="group.targetIds" placeholder="请选择目标" multiple filterable> 
                  <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id">{{target.company}}</Option>
                </Select>-->
              <Row>
                <Checkbox v-model="group.checkAllUser" @on-change="selectAllUser($event, group)"
                :disabled="group.targetTeamData.map(item => item.id).every(id => group.initTargetIds.includes(id))">全选</Checkbox
                >
                <Input
                  v-model.trim="queryTargetTeamInfo.name"
                  placeholder="名称"
                  style="width:150px"
                  clearable
                  @on-change="changeTargetTeamPage(1, group)"
                ></Input>
                <Input
                  v-model.trim="queryTargetTeamInfo.groupName"
                  placeholder="分组"
                  style="width:150px"
                  clearable
                  @on-change="changeTargetTeamPage(1, group)"
                ></Input>
                <Page
                  :total="group.targetTeamTotal"
                  :current="queryTargetTeamInfo.pageIndex"
                  :page-size="queryTargetTeamInfo.pageSize"
                  @on-change="changeTargetTeamPage($event, group)"
                  show-total
                  show-elevator
                  size="small"
                  style="float:right"
                />
              </Row>
              <CheckboxGroup
                v-model="group.targetIds"
                @on-change="changeCompanySelect($event, group)"
              >
                <Checkbox
                  :label="target.id"
                  v-for="target in group.targetTeamData"
                  :key="target.id"
                  :disabled="group.initTargetIds.includes(target.id)"
                >
                  <span
                    >{{ target.name }}（{{ target.groupName || '无' }}）（{{
                      target.category ? filterCategory(target.category) : '无'
                    }}）</span
                  >
                </Checkbox>
              </CheckboxGroup>
            </FormItem>
            <!-- <Divider dashed style="margin:10px 0"></Divider>-->
          </div>
        </Form>
      </Modal>
      <!--<Modal v-model="modifyTargetModal.show" 
        :title="modifyTargetModal.title" 
        :loading = "modifyTargetModal.loading"
        width="600px" 
        :mask-closable = "false"
        @on-cancel="handleReset('allotFormValidate')"
        @on-ok="modifyTargetAllot">
        <Form ref="allotFormValidate" :model="allotFormValidate" :rules="ruleValidate" :label-width="100">
          <FormItem label="目标" prop="basicTargetId">
            <Select filterable v-model="allotFormValidate.basicTargetId" placeholder="请选择目标" @on-change="changeTarget" filterable> 
              <Option  v-for="target in targetTeamData" :value="target.id" :key="target.id">{{target.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="团队" prop="teamId">
            <Select filterable  v-model="allotFormValidate.teamId" placeholder="请选择团队">
              <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="子网络" prop="subnetId">
            <Select filterable  v-model="allotFormValidate.subnetId" placeholder="请选择子网络" @on-change="changeSubnet">
              <! --<Option value="all">所有</Option>-->
      <!--<Option  v-for="item in subnetList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="虚拟机" prop="vmId" v-if="modifyTargetModal.show">
            <Select filterable v-model="allotFormValidate.vmId" placeholder="请选择虚拟机" filterable>
              <Option v-for="item in vmlists" :value="item.id" :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem  label="是否显示" prop="visibility">
            <RadioGroup v-model="allotFormValidate.visibility">
              <Radio :label=1>显示</Radio>
              <Radio :label=0>不显示</Radio>
            </RadioGroup>
            <span style="color:#f90" v-if="type == 4"> <Icon type="ios-information-circle-outline"/>用于在演练页面的展示控制</span>
            <span style="color:#f90" v-if="type == 1"> <Icon type="ios-information-circle-outline"/>用于在竞赛页面的展示控制</span>
          </FormItem>
        </Form>
      </Modal>-->
      </search-table>
</template>

<script>
import {
  queryAllotTopoTargetList,
  allotTopoTarget,
  getTopoTargetList,
  delTopoTargetAllot,
  getSceneTeamTarget,
  changeAvailable,
  batchAllotTopoTarget,
  batchDeleteTopoAllotTarget
} from '@/api/drill_compete';
import { getaccessgrouplist } from '@/api/access_new';
import { allDirection } from '@/api/dict';
import { debounce } from '@/libs/utils';
import { categoryMixin } from '../hw/mixins';
export default {
  name: 'scenes',
  props: ['type', 'disabledAllBtn'],
  components: {  },
  mixins: [categoryMixin],
  data() {
    const validateNum = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^([1-9]|[1-9]\\d|100)$');
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('请输入1-100的整数'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      teamName: '',
      routeParams: {
        id: this.$route.query.id,
        prjid: this.$route.query.prjid
      },
      targetModal: {
        show: false,
        title: '目标分配',
        loading: true,
        type: 1 //1添加，2修改
      },
      modifyTargetModal: {
        show: false,
        title: '修改分配',
        loading: true
      },
      pathList: [],
      accessGroupList: [],
      vmlists: [],
      allVms: [],
      teamlists: [],
      queryTargetTeamInfo: {
        pageIndex: 1,
        pageSize: 200,
        available: 1,
        publicTarget:false,
        // sceneId:this.$route.query.id,
        industry: '',
        projectId: this.$route.query.prjid
      },
      queryTargetAllotInfo: {
        pageIndex: 1,
        pageSize: 10,
        projectId: this.$route.query.prjid,
        sceneId: this.$route.query.id
      },
      questionList: [],
      access: '1',
      formValidate: {
        accessGroupList: []
      },
      allotFormValidate: {
        createTime: '',
        externalIp: '',
        externalPort: '',
        externalServicePort: '',
        id: '',
        sceneId: '',
        subnetId: '',
        subnetName: '',
        targetId: '',
        targetName: '',
        teamId: '',
        teamName: '',
        visibility: 0,
        vmId: '',
        vmName: ''
      },
      oldFormValidate: {},
      ruleValidate: {
        subnetId: [{ required: true, message: '请选择子网络', trigger: 'change' }],
        questionId: [{ required: true, message: '请选择题目', trigger: 'change' }],
        visibility: [{ required: true, type: 'number', message: '请选择', trigger: 'change' }],
        vmId: [{ required: true, message: '请选择虚拟机', trigger: 'change' }],
        teamId: [{ required: true, message: '请选择团队', trigger: 'change' }],
        targetIds: [{ required: true, type: 'error', message: '请选择目标', trigger: 'change' }],
        basicTargetId: [{ required: true, message: '请选择目标', trigger: 'change' }],
        idsTOS: [
          {
            required: true,
            type: 'array',
            min: 1,
            message: '请添加人员设备',
            trigger: 'change'
          }
        ]
      },
      querytime: {},
      targetTeamCol: [
        //        {
        //          type: 'index',
        //          align: 'center',
        //          ellipsis:true,
        ////          width:60
        //        },
        {
          type:'selection',
          width:60
        },
        {
          title: '团队名称',
          key: 'teamName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-left',
          width: 240
        },
        {
          title: '单位',
          key: 'company',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          placement: 'top-left'
        },
        {
          title: '名称',
          key: 'name',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          placement: 'top-left'
        },
        {
          title: '分组',
          key: 'groupName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100
        },
        {
          title: '类别',
          key: 'category',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 100,
          placement: 'top-left',
          render: (h, { row: { category } }) => {
            return h('span', this.filterCategory(category));
          }
        },
        {
          title: 'Url地址',
          key: 'url',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 300
        },
        {
          title: '行业',
          key: 'industryName',
          align: 'center',
          tooltip: true,
          width: 80
        },
        {
          title: '区域',
          key: 'district',
          align: 'center',
          tooltip: true,
          width: 66
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'center',
          ellipsis: true
          //          width:100
        },
        {
          title: '是否可用',
          key: 'available',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-right',
          render: (h, params) => {
            return h(
              'Button',
              {
                style: {
                  cursor: 'text!important'
                },
                props: {
                  type: params.row.available == 1 ? 'success' : 'default',
                  size: 'small',
                  ghost: params.row.available == 1
                }
              },
              params.row.available == 1 ? '是' : '否'
            );
            return h(
              'Poptip',
              {
                props: {
                  confirm: true,
                  'ok-text': '确定',
                  'cancel-text': '取消',
                  type: 'error',
                  size: 'large',
                  title: `你确定要${params.row.available == 1 ? '下线' : '上线'}目标吗?`,
                  transfer: true
                },
                on: {
                  'on-ok': () => {
                    this.changeAvailable(params.row);
                  }
                }
              },
              [
                h(
                  'Button',
                  {
                    props: {
                      type: params.row.available == 1 ? 'success' : 'default',
                      size: 'small',
                      ghost: params.row.available == 1
                    }
                  },
                  params.row.available == 1 ? '是' : '否'
                )
              ]
            );
          }
        },
        // {
        //   title:'版本信息',
        //   key:'edition',
        //   tooltip:true
        // },
        {
          title: '操作',
          key: 'action',
          ellipsis: true,
          width: 100,
          placement: 'top-right',
          action: true,
          opList:[
            {
                txt:'删除',
                type:'delete',
                tooltip:true,
                disabled:() => this.disabledAllBtn,
                fun:(data) => {
                    this.delTopoTargetAllot(data.id)
                },
                title: '你确定要删除吗?'
            }
          ],
          // render: (h, params) => {
          //   return h('div', [
              //	                h('Button',{
              //	                  props:{
              //	                    type:'primary',
              //	                    size:'small'
              //	                  },
              //	                  style:{
              //	                    marginRight:'5px'
              //	                  },
              //	                  on:{
              //	                    click:()=>{
              //	                      //this.showAddAndUpdate(params.row)
              //	                      this.modifyTargetModal.show = true;
              //	                      this.allotFormValidate = JSON.parse(JSON.stringify(params.row));
              //	                      this.getAllVmlist();
              //	                    }
              //	                  }
              //	                },'修改'),
              // h(
              //   'Poptip',
              //   {
              //     props: {
              //       confirm: true,
              //       'ok-text': '确定',
              //       'cancel-text': '取消',
              //       type: 'error',
              //       size: 'large',
              //       title: '你确定要删除吗?',
              //       transfer: true
              //     },
              //     on: {
              //       'on-ok': () => {
              //         this.delTopoTargetAllot(params.row.id);
              //       }
              //     }
              //   },
              //   [
              //     h(
              //       'Button',
              //       {
              //         props: {
              //           type: 'error',
              //           size: 'small',
              //           disabled: this.disabledAllBtn
              //         },
              //         style: {
              //           border: 'none',
              //           background: 'none',
              //           boxShadow: 'none'
              //         }
              //       },
              //       [
              //         h('img', {
              //           attrs: {
              //             //                          src: !this.setReBtnStatus(params.row) ?require('../../../assets/globalIcon/del.png'):require('../../../assets/globalIcon/dis-del.png'),
              //             src: this.disabledAllBtn
              //               ? require('../../../../assets/project/delNote-d.png')
              //               : require('../../../../assets/project/delNote-h.png')
              //           },
              //           style: {
              //             cursor: 'pointer',
              //             //				                            'margin-right':'5px',
              //             'vertical-align': 'middle',
              //             //				                            width:'16px',
              //             //				                            height:'auto',
              //             display: 'inline-block',
              //             marginBottom: '4px'
              //           }
              //         })
                      //	                    h('span',{
                      //	                        style: {
                      //	                            cursor: 'pointer',
                      //	//                          color:!this.setReBtnStatus(params.row) ? '#2d8cf0' : '#c5c8ce'
                      //															color:'#2d8cf0'
                      //	                        },
                      //	                    },'删除')
            //         ]
            //       )
            //     ]
            //   )
            // ]);
          // }
        }
      ],
      idsTOSCol: [
        {
          title: '团队',
          key: 'teamName',
          align: 'center',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '子网络',
          key: 'subnetName',
          align: 'center',
          ellipsis: true,
          tooltip: true
        },
        {
          title: '虚拟机',
          key: 'vmName',
          align: 'center',
          ellipsis: true,
          tooltip: true
        },
        //	          {
        //	            title:'外网IP',
        //	            key:'externalIp',
        //	            align:'center',
        //	            ellipsis:true,
        //	            tooltip:true,
        //	          },
        //	          {
        //	            title:'外网端口',
        //	            key:'externalPort',
        //	            align:'center',
        //	            ellipsis:true,
        //	            tooltip:true,
        //	          },
        {
          title: '显示状态',
          key: 'score',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color: params.row.visibility == 1 ? 'success' : 'default',
                  type: 'border'
                },
                on: {
                  click: () => {
                    //this.showAddAndUpdate(params.row)
                  }
                }
              },
              params.row.visibility == 1 ? '是' : '否'
            );
          }
        },
        {
          title: '操作',
          key: 'os',
          ellipsis: true,
          //	            width:200,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      let index = this.formValidate.idsTOS.findIndex(
                        (item) => item.id == params.row.id
                      );
                      this.formValidate.idsTOS.splice(index, 1);
                    }
                  }
                },
                '移除'
              )
            ]);
          }
        }
      ],
      targetTeamData: [],
      targetTeamTotal: 0,
      TargetId: '',
      projectInfo: {},
      subnetList: [],
      networkId: '',
      teamArr: [],
      networkArr: [],
      vmArr: [],
      idwithName: {},
      targetAllotList: [],
      targetAllotTotal: 0,
      selectTargetTeams:[],
      targetTeamDataCopy: [],
      industryList: [],
      companyList: [], //所有单位列表
      assignLoading: false,
      selectAll: false
    };
  },
  filters: {},
  computed: {
    showQuestionList() {
      //选出部署了题目镜像虚拟机的题目
      let quesList = [];
      this.questionList.forEach((ques) => {
        if (this.allVms.map((vm) => vm.imageName).includes(ques.imageName)) {
          quesList.push(ques);
        }
      });
      return quesList;
    },
    checkTargetIds() {
      return this.selectTargetTeams.map((item) => item.id);
    }
  },
  async mounted() {
    await this.getIndustryTypes();
    this.getAccessGroupList();
    this.getAllTargetTeam();
    this.queryTargetAllot();
  },
  methods: {
    // 分配目标的模态框关闭后清空搜索条件
    targetModalVisibleChange(type) {
      if (!type) {
        this.queryTargetTeamInfo.pageIndex = 1;
        this.queryTargetTeamInfo.pageSize = 200;
        this.queryTargetTeamInfo.industry = '';
        this.queryTargetTeamInfo.company = '';
        this.queryTargetTeamInfo.category = '';
        this.queryTargetTeamInfo.name = '';
        this.queryTargetTeamInfo.groupName = '';
        this.teamName = '';
      }
    },
    // 获取行列列表
    getIndustryTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwIndustryTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.industryList = list;
          })
          .catch(() => {
            this.$Message.error('获取行业列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    //  	getProjectInfo(){
    //			getstatusbyprjid(this.$route.query.prjid).then(data => {
    //				if(data.code == 1){
    //					this.projectInfo = data.attribute;
    //					this.getProjectSubnet();
    //				}
    //			})
    //		},
    setCheckAll(group) {
      let curTargetIds = group.targetIds;
      let allTargetIds = group.targetTeamData.map((item) => item.id);
      if (allTargetIds.length > 0 && allTargetIds.every((item) => curTargetIds.includes(item))) {
        group.checkAllUser = true;
      } else {
        group.checkAllUser = false;
      }
    },
    getTargetTeamList: debounce(function(group) {
      if (this.targetTeamLoading) {
        this.hasNoExecuteRequest = true;
        return;
      }
      this.targetTeamLoading = true;
      // this.queryTargetTeamInfo.name = group ? group.queryName : '';
      // this.queryTargetTeamInfo.groupName = group ? group.queryGroupName : '';
      getTopoTargetList(this.queryTargetTeamInfo)
        .then((data) => {
          this.targetTeamLoading = false;
          if (data.code == 1) {
            //	  				this.targetTeamData = data.data.items || data.data;
            //	  				this.targetTeamDataCopy = data.data.items || data.data;
            //	  				this.targetTeamData.forEach(team => {
            //	  					this.idwithName[team.id] = team;
            //					})
            if (!group) {
              //最上方的单位和类别查询
              this.formValidate.accessGroupList.forEach((group) => {
                group.targetTeamData = data.data.items || data.data;
                group.targetTeamTotal = data.data.total;
                this.setCheckAll(group);
              });
            } else {
              group.targetTeamData = data.data.items || data.data;
              group.targetTeamTotal = data.data.total;
              this.setCheckAll(group);
            }
            if (this.hasNoExecuteRequest) {
              this.getTargetTeamList(group);
              this.hasNoExecuteRequest = false;
            }
          } else {
            if (this.hasNoExecuteRequest) {
              this.getTargetTeamList(group);
              this.hasNoExecuteRequest = false;
            }
          }
        })
        .catch((error) => {
          this.targetTeamLoading = false;
        });
    }, 500),
    getAllTargetTeam() {
      let params = {
        pageIndex: 1,
        pageSize: 2147483646,
        projectId: this.$route.query.prjid
      };
      getTopoTargetList(params).then((data) => {
        if (data.code == 1) {
          let targetData = data.data.items;
          data.data.items.forEach((team) => {
            this.idwithName[team.id] = team;
          });
          // 所有单位列表
          this.companyList = [...new Set(targetData.map((target) => target.company))];
          this.targetTeamTotal = data.data.total;
        }
      });
    },
    // debounceSearch:debounce(function(page, group){
    //   this.changeTargetTeamPage(page, group)
    // },500),
    changeTargetTeamPage(page, group) {
      group.queryPage = page;
      this.queryTargetTeamInfo.pageIndex = page;
      this.getTargetTeamList(group);
    },
    initData() {
      this.formValidate = {
        accessGroupList: []
      };
    },
    getAllVmlist() {
      let _this = this;
      let params = {
        page: 1,
        pageSize: 10000,
        sortBy: 'name',
        order: 'asc',
        findPorts: true
      };
      if (this.formValidate.targetId) {
        params.imageId = this.idwithName[this.formValidate.targetId].imageId;
      }
      if (this.allotFormValidate.basicTargetId) {
        params.imageId = this.idwithName[this.allotFormValidate.basicTargetId].imageId;
      }
      if (this.group) {
        //params.party = this.group.partyId;
      }
      if (this.targetModal.show && this.formValidate.subnetId) {
        params.networkId = this.formValidate.subnetId;
      }
      if (this.modifyTargetModal.show && this.allotFormValidate.subnetId) {
        params.networkId = this.allotFormValidate.subnetId;
      }
      if (this.modifyTargetAllot.show && this.allotFormValidate.subnetId) {
        params.networkId = this.allotFormValidate.subnetId;
      }
      queryVmWithParty(this.routeParams.prjid, params).then((data) => {
        //		    getProjectSevers(params).then(data => {
        if (data.code == 1) {
          this.vmlists = data.data.list || data.data;
          if (this.targetModal.show && this.vmlists.length > 0) {
            this.formValidate.vmId = this.vmlists[0].id;
            this.formValidate.vmName = this.vmlists[0].name;
            //			    		this.queryTargetAllotRelation();
            //	    		this.formValidate.idsTOS = [];
          } else if (this.modifyTargetModal.show && this.vmlists.length > 0) {
            //			       	    _this.$nextTrick(() => {
            //
            //			       	    })
            //			    		setTimeout(() => {
            //			    			this.allotFormValidate.vmId = this.vmlists[0].id;
            //			    			this.allotFormValidate.vmName = this.vmlists[0].name;
            //			    		},500)
          }
          this.vmlists.forEach((vm) => {
            this.idwithName[vm.id] = {
              id: vm.id,
              name: vm.name
            };
          });
          //this.getVmIp(this.formValidate.vmId);
          //					if(this.vmlists.length > 0){
          //						let server = this.vmlists.filter(vm => vm.id == this.formValidate.vmId)[0];
          //	    		        if(server){
          //	    		        	this.formValidate.subnet = server.addresses[0].subnetId;
          //	    		        	this.getFlagServerList(server.address[0].ipv4);
          //	    		        	this.getFlagServerList(server.addresses[0].ip);
          //	    		        }
          //					}
        }
      });
    },
    // 防抖封装，团队名改变时，延迟更新列表数据
    getDataBounce: debounce(function() {
      if (!this.teamName) {
        return;
      }
      // this.getAccessGroupList();
      this.queryTargetTeamInfo.pageIndex = 1;
      this.selectGroupList = [];
      this.formValidate.accessGroupList = [];
      this.formValidate.accessGroupList = this.accessGroupList.filter(
        (item) => item.name === this.teamName
      ); //data.data.items.filter(item => item.name !== '目标方管理员组' && item.creatorName !='内部服务用户');
      this.formValidate.accessGroupList.forEach((group) => {
        this.$set(group, 'checkAllUser', false);
        this.$set(group, 'targetIds', []);
        this.$set(group, 'initTargetIds', []);
        this.$set(group, 'selectableTargets', []);
        this.$set(group, 'targetTeamData', []);
        this.$set(group, 'targetTeamTotal', 0);
        this.$set(group, 'queryName', '');
        this.$set(group, 'queryGroupName', '');
        this.$set(group, 'queryPage', 1);
      });
      this.getTargetTeamList();
      this.getSceneTeamTarget();
    }),
    getAccessGroupList() {
      if (!this.routeParams.id) {
        return;
      }
      let params = {
        pageIndex: 1,
        pageSize: 2147483647,
        testId: this.routeParams.id
        // name: this.teamName
      };
      this.selectGroupList = [];
      this.formValidate.accessGroupList = [];
      getaccessgrouplist(params).then((data) => {
        if (data.code == 1) {
          let accessGroupList = data.data.items.filter(
            (item) => item.name !== '目标方管理员组' && item.creatorName != '内部服务用户'
          );
          this.accessGroupList = accessGroupList;
          // this.teamName = accessGroupList[0].name;
          // this.formValidate.accessGroupList = [accessGroupList[0]]; //data.data.items.filter(item => item.name !== '目标方管理员组' && item.creatorName !='内部服务用户');
          // this.formValidate.accessGroupList.forEach((group) => {
          //   this.$set(group, 'checkAllUser', false);
          //   this.$set(group, 'targetIds', []);
          //   this.$set(group, 'selectableTargets', []);
          //   this.$set(group, 'targetTeamData', []);
          //   this.$set(group, 'targetTeamTotal', 0);
          //   this.$set(group, 'queryName', '');
          //   this.$set(group, 'queryGroupName', '');
          //   this.$set(group, 'queryPage', 1);
          // });
          // this.getTargetTeamList();
          // this.getSceneTeamTarget();
        } else if (data.code == -2) {
          this.accessGroupList = [];
        } else {
          this.$Message.warning(data.message);
        }
      });
    },
    getGroupInfo(id) {
      this.formValidate.group = this.formValidate.accessGroupList.find((group) => group.id === id);
    },
    showAddAndUpdate(info) {
      this.targetModal.show = true;
      this.teamName = this.accessGroupList[0].name;
      this.getDataBounce();
      // this.formValidate.accessGroupList.forEach((item) => {
      //   item.targetIds = [];
      // });
      // this.getAccessGroupList();
      if (this.targetAllotTotal > 0) {
      }
      if (!info) {
        this.targetModal.type = 1;
      } else {
        this.targetModal.type = 2;
      }
    },
    handleReset(name) {
      //	        this.$refs[name].resetFields();
      this.addTarget = false;
      this.initData();
      this.$refs[name].fields.forEach(function(e) {
        if (e.fieldValue != undefined && e.fieldValue != '') {
          e.resetField();
        }
      });
    },
    addTargetTeam() {
      let params = JSON.parse(JSON.stringify(this.formValidate));
      params.questionName = this.question.name;
    },
    modifyTargetTeam() {
      let params = JSON.parse(JSON.stringify(this.formValidate));
      params.questionName = this.question.name;
    },
    saveTargetTeam() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          if (this.targetModal.type == 1) {
            this.addTargetTeam();
          } else {
            this.modifyTargetTeam();
          }
        } else {
          this.cancelLoading('targetModal');
        }
      });
    },
    getTargetSize(size) {
      this.queryTargetAllotInfo.pageSize = size;
      this.queryTargetAllot();
    },
    getTargetPage(page) {
      this.queryTargetAllotInfo.pageIndex = page;
      this.queryTargetAllot();
    },
    changeTeamGroup() {},
    changeTarget(targetId) {
      if (this.targetModal.show) {
        this.formValidate.vmId = '';
        this.formValidate.vmName = '';
        this.formValidate.subnetId = '';
        this.formValidate.subneName = '';
        this.formValidate.teamId = '';
        this.formValidate.teamName = '';
        this.queryTargetAllotRelation();
      } else if (this.modifyTargetModal.show) {
        this.allotFormValidate.vmId = '';
        this.allotFormValidate.vmName = '';
      }
      this.getAllVmlist();
    },
    changeSubnet(id) {
      if (!id) {
        return;
      }
      //	    	if(this.targetModal.show){
      //	    		this.formValidate.vmId = '';
      //	    		this.formValidate.vmName = '';
      //	    		this.queryTargetAllotRelation();
      ////	    		this.formValidate.idsTOS = [];
      //	    	}else if(this.modifyTargetModal.show){
      //	    		this.allotFormValidate.vmId = '';
      //	    		this.allotFormValidate.vmName = '';
      //	    	}
      this.formValidate.externalIp = this.idwithName[this.formValidate.subnetId].ip;
      this.getAllVmlist();
    },
    changeVm() {},
    getProjectSubnet() {
      queryNetworkList(this.$route.query.prjid, this.projectInfo.network.id).then((data) => {
        if (data.code == 1) {
          let subnetList = [];
          let linkList = [];
          data.attribute.editorStage.childs.forEach((item) => {
            subnetList = subnetList.concat(item.childs);
            if (item.links) {
              linkList = linkList.concat(item.links);
            }
          });
          this.subnetList = subnetList.filter((subnet) => subnet.dataType == 'NW');
          this.subnetList.forEach((subnet) => {
            let ip;
            if (this.type == 1) {
              if (linkList.filter((link) => link.rightNetId == subnet.id).length > 0) {
                ip = linkList.filter((link) => link.rightNetId == subnet.id)[0].rightIpParts[0]
                  .ipAddress; //新接口这个字段没有了
              }
            }
            this.idwithName[subnet.id] = {
              id: subnet.id,
              name: subnet.name,
              ip: ip
            };
          });
        }
      });
    },
    addIdTOS() {
      this.$refs['addFormValidate'].validate((valid) => {
        if (valid) {
          //	            	if(this.targetModal.type == 1){
          //	            		this.addTargetTeam();
          //	            	}else{
          //	            		this.modifyTargetTeam();
          //	            	}
          this.formValidate.idsTOS.push({
            vmId: this.idwithName[this.formValidate.vmId].id,
            vmName: this.idwithName[this.formValidate.vmId].name,
            teamId: this.idwithName[this.formValidate.teamId].id,
            teamName: this.idwithName[this.formValidate.teamId].name,
            subnetId: this.formValidate.subnetId,
            subnetName: this.idwithName[this.formValidate.subnetId].name,
            externalIp: this.formValidate.externalIp, //对外ip
            externalPort: this.formValidate.externalPort, //对外端口
            externalServicePort: this.formValidate.externalServicePort,
            visibility: this.formValidate.visibility
          });
          //	            }else{
          ////	            	this.cancelLoading('targetModal');
        }
      });
    },
    batchAllotTopoTarget() {
      this.assignLoading = true;
      batchAllotTopoTarget(this.$route.query.id)
        .then((res) => {
          let { code, data, message } = res;
          if (code === 1) {
            this.$Message.info('分配完成');
            this.getTargetPage(1);
          } else {
            this.$Message.error(message);
          }
          this.assignLoading = false;
        })
        .catch((error) => {
          this.assignLoading = false;
          this.$Message.info('分配失败');
        });
    },
    targetAllot() {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          let sceneId = this.$route.query.id;
          let params = this.formValidate.accessGroupList.map((group) => {
            return {
              projectId: this.$route.query.prjid,
              sceneId: sceneId,
              targets: group.targetIds.map((id) => {
                return {
                  name: this.idwithName[id].name,
                  company: this.idwithName[id].company,
                  publicTarget: this.idwithName[id].publicTarget,
                  tagetId: id
                };
              }),
              teamId: group.id,
              teamName: group.name
            };
          });
          allotTopoTarget(params, sceneId)
            .then((data) => {
              if (data.code == 1) {
                // 添加成功后清空搜索条件，回退到首页
                this.queryTargetAllotInfo.pageIndex = 1;
                this.queryTargetAllotInfo.teamName = '';
                this.queryTargetAllotInfo.company = '';
                this.queryTargetAllotInfo.url = '';
                this.$emit('add-data');
                this.queryTargetAllot();
                this.targetModal.show = false;
                //			   	    		this.formValidate.vmId = '';
                //			   	    		this.formValidate.teamId = '';
                //			   	    		this.formValidate.visibility = 0;
              } else {
                this.$Message.warning(data.message);
                this.cancelLoading('targetModal');
              }
            })
            .catch((error) => {
              this.$Message.error(error);
              this.cancelLoading('targetModal');
            });
        } else {
          this.cancelLoading('targetModal');
        }
      });
    },
    VRIPRelation() {
      let params = this.formValidate.idsTOS.map((item) => {
        return {
          contestId: this.$route.query.id,
          ip: this.idwithName[this.formValidate.targetId].ip,
          targetName: this.idwithName[this.formValidate.targetId].name,
          teamId: item.teamId,
          teamName: item.teamName,
          virtualRouterIP: item.externalIp,
          vmname: item.vmName
        };
      });
      VRIPRelation(params).then((data) => {
        if (data.code == 1) {
        }
      });
    },
    //queryTargetAllot,queryTargetAllotRelation,modifyTargetAllot
    queryTargetAllot() {
      queryAllotTopoTargetList(this.queryTargetAllotInfo)
        .then((data) => {
          if (data.code == 1) {
            let list = data.data.items;
            this.targetAllotList = list.map((item) => {
              item.industryName = this.getIndustryName(item.industry);
              return item;
            });
            this.targetAllotTotal = data.data.total;
            this.selectAll = false;
          } else {
            this.$Message.warning(data.message);
          }
        })
        .catch((error) => {
          this.$Message.error(error);
        });
    },
    // 将行业Id转换为对应的名称
    getIndustryName(industryId) {
      let item = this.industryList.find((item) => item.dictid === industryId);
      // 返回对应的名称，没有查到数据，还是返回ID
      return item ? item.dictname : industryId;
    },
    queryTargetAllotRelation() {
      let params = {
        pageIndex: 1,
        pageSize: 1000,
        //	   	   	   subnetId:this.formValidate.subnetId,
        basicTargetId: this.formValidate.targetId,
        sceneId: this.$route.query.id
      };
      queryTargetAllotRelation(params)
        .then((data) => {
          if (data.code == 1) {
            this.formValidate.idsTOS = data.data.items;
            //	   				if(data.data.items.length > 0){
            //	   					this.formValidate.subnetId = data.data.items[0].subnetId;
            //	   					this.formValidate.subnetName = data.data.items[0].subnetName;
            //	   					this.getAllVmlist();
            //	   				}
          } else {
            this.$Message.warning(data.message);
          }
        })
        .catch((error) => {
          this.$Message.error(error);
        });
    },
    modifyTargetAllot() {
      this.$refs['allotFormValidate'].validate((valid) => {
        if (valid) {
          let params = {
            createTime: this.allotFormValidate.createTime,
            externalIp: this.allotFormValidate.externalIp,
            externalPort: this.allotFormValidate.externalPort,
            externalServicePort: this.allotFormValidate.externalServicePort,
            id: this.allotFormValidate.id,
            sceneId: this.allotFormValidate.sceneId,
            subnetId: this.allotFormValidate.subnetId,
            subnetName: this.idwithName[this.allotFormValidate.subnetId].name,
            basicTargetId: this.allotFormValidate.basicTargetId,
            targetName: this.idwithName[this.allotFormValidate.basicTargetId].name,
            company: this.idwithName[this.allotFormValidate.basicTargetId].company,
            teamId: this.allotFormValidate.teamId,
            teamName: this.idwithName[this.allotFormValidate.teamId].name,
            visibility: this.allotFormValidate.visibility,
            vmId: this.allotFormValidate.vmId,
            vmName: this.idwithName[this.allotFormValidate.vmId].name
          };
          modifyTargetAllot(params.id, params)
            .then((data) => {
              if (data.code == 1) {
                this.$emit('update-data');
                this.queryTargetAllot();
                this.modifyTargetModal.show = false;
                this.cancelLoading('modifyTargetModal');
                this.$Message.info('操作成功');
              } else {
                this.$Message.warning(data.message);
              }
            })
            .catch((error) => {
              this.$Message.error(error);
              this.cancelLoading('modifyTargetModal');
            });
        } else {
          this.cancelLoading('modifyTargetModal');
        }
      });
    },
    cancelLoading(name) {
      this[name].loading = false;
      setTimeout(() => {
        this[name].loading = true;
      });
    },
    closeTargetModal() {
      this.addTarget = false;
      //	    	this.handleReset('formValidate');
      //	    	this.handleReset('addFormValidate');
    },
    delTopoTargetAllot(id) {
      delTopoTargetAllot(id)
        .then((data) => {
          if (data.code == 1) {
            this.$Message.info('删除成功');
            // 删除后展示当前页，当前页没有数据展示前一页
            this.queryTargetAllotInfo.pageIndex =
              this.targetAllotList.length == 1 && this.queryTargetAllotInfo.pageIndex > 1
                ? this.queryTargetAllotInfo.pageIndex - 1
                : this.queryTargetAllotInfo.pageIndex;
            this.$emit('delete-data');
            this.queryTargetAllot();
            this.$refs.searchTable.delSelectItem(id);
          } else {
            this.$Message.warning(data.message);
          }
        })
        .catch(() => {
          this.$Message.error('删除异常');
        });
    },
    // 点击全选
    selectAllChange(val) {
      this.targetAllotList.forEach((item) => {
        this.$set(item, 'checked', val);
      });
    },
    // 修改全选的状态
    changeSelectAll(state, item) {
      for (let i = 0, length = this.targetAllotList.length; i < length; i++) {
        if (item.id === this.targetAllotList[i].id) {
          this.$set(this.targetAllotList[i], 'checked', state);
        }
        if (!this.targetAllotList[i].checked) {
          this.selectAll = false;
          return;
        }
      }
      this.selectAll = true;
    },
    batchDeleteTopoAllotTarget() {
      let ids = this.checkTargetIds;
      batchDeleteTopoAllotTarget(ids)
        .then((res) => {
          let { code, data, message } = res;
          if (code == 1) {
            this.$Message.info('删除成功');
            // 删除后展示当前页，当前页没有数据展示前一页
            this.queryTargetAllotInfo.pageIndex =
              this.targetAllotList.length == ids.length && this.queryTargetAllotInfo.pageIndex > 1
                ? this.queryTargetAllotInfo.pageIndex - 1
                : this.queryTargetAllotInfo.pageIndex;
            this.$emit('delete-data');
            this.queryTargetAllot();
            this.selectTargetTeams = [];
          } else {
            this.$Message.error(message);
          }
        })
        .catch(() => {
          this.$Message.error('删除异常');
        });
    },
    getSceneTeamTarget() {
      getSceneTeamTarget(this.$route.query.id).then((data) => {
        if (data.code == 1 && data.data.items.length > 0) {
          this.formValidate.accessGroupList.forEach((group) => {
            let team = data.data.items.filter((item) => item.teamId == group.id);
            if (team.length > 0) {
              //再存一份，之前选中的要禁用
              group.initTargetIds = [...new Set(team[0].targets.map((target) => target.tagetId))];
              group.targetIds = [...new Set(team[0].targets.map((target) => target.tagetId))];
              this.setCheckAll(group);
            }else{
              group.initTargetIds = [];
              group.targetIds = []
            }
          });
          //	    			this.formValidate.accessGroupList = data.data.items.map(item => {
          //	    				return {
          //	    					id:item.teamId,
          //	    					name:item.teamName,
          //	    					targetIds:item.targets.map(target => target.tagetId)
          //	    				}
          //	    			});
          //this.changeTarget()
        }
      });
    },
    changeAvailable(item) {
      changeAvailable(item.id, { available: !item.available })
        .then((data) => {
          if (data.code == 1) {
            this.$Message.info('操作成功');
            this.queryTargetAllot();
          } else {
            this.$Message.warning(data.message);
          }
        })
        .catch(() => {
          this.$Message.error('操作异常');
        });
    },
    changeTarget() {
      let selectedTargets = [];
      this.formValidate.accessGroupList.forEach((group) => {
        selectedTargets = selectedTargets.concat(group.targetIds); //所有已经选择过得目标
      });
      let unSelectableTargets = this.targetTeamDataCopy
        .filter((target) => !selectedTargets.includes(target.id))
        .map((target) => target.id);
      this.formValidate.accessGroupList.forEach((group) => {
        group.selectableTargets = [...unSelectableTargets, ...group.targetIds].map((id) => {
          return this.idwithName[id];
        });
      });
    },
    selectAllUser(status, group) {
      let allTargetIds = group.targetTeamData.map((item) => item.id);
      let curTargetIds = group.targetIds;
      if (status) {
        allTargetIds.forEach((id) => {
          if (!curTargetIds.includes(id)) {
            group.targetIds.push(id);
          }
        });
      } else {
        group.targetIds = curTargetIds.filter((item) => !allTargetIds.includes(item));
      }
    },
    changeCompanySelect(curTargetIds, curGroup) {
      this.formValidate.accessGroupList.forEach((group) => {
        if (group.id != curGroup.id) {
          group.targetTeamData.forEach((target) => {
            if (
              curTargetIds.includes(target.id) &&
              group.targetIds.includes(target.id) &&
              !target.publicTarget
            ) {
              //选中时，取消其他组此目标的选中
              group.targetIds.splice(
                group.targetIds.findIndex((id) => id == target.id),
                1
              );
            }
          });
        } else {
          this.setCheckAll(group);
        }
      });
    }
  }
};
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
.targetHeader {
  /*padding: 10px;*/
  margin-top: 15px;
  margin-bottom: 7px;
  /* overflow: hidden; */
  display: flex; 
  justify-content: space-around;
}
.account-target-modal /deep/ .ivu-modal {
  height: calc(100vh - 200px);
  min-height: 520px;
}
.account-target-modal /deep/ .ivu-modal .ivu-modal-content {
  height: 100%;
}
.account-target-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body {
  height: calc(100% - 112px);
}
.search-group {
  width: calc(100% + 32px);
  margin-left: -16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8eaec;
}
.account-target-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body > form {
  height: calc(100% - 65px);
  overflow: auto;
}
.query-box {
  display: flex; 
  align-items: center; 
  flex: 1; 
  flex-wrap: wrap;
}
</style>
